﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Vue.Admin.Models;
using Vue.Admin.Models;
using Vue.Admin.Tools;

namespace Vue.Admin.Api.Controllers
{
    /// <summary>
    /// 角色
    /// </summary>
    [Authorize]
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class RolesController : ControllerBase
    {
        #region 注入数据库上下文
        private readonly DBContext _dbContext;

        public RolesController(DBContext db)
        {
            this._dbContext = db;
        }
        #endregion

        #region 获取角色树列表
        /// <summary>
        /// 获取角色树列表
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> GetRoleTreeGrid()
        {
            List<ESysRoles> roles = await _dbContext.ESysRoles.ToListAsync<ESysRoles>();
            List<TreeGridDto> treeGrids = new List<TreeGridDto>();

            foreach (var item in roles.Where(x => x.FparentId == 0))
            {
                var tree = new TreeGridDto
                {
                    nodeId = item.Fid,
                    nodeName = item.Fname,
                    nodeParentId = item.FparentId,
                    nodeSort = item.Fsort,
                    nodeRemark = item.Fremark,
                    nodeAddTime = item.FaddTime,
                    Childrens = GetChildrenTreeGridNode(roles, item)
                };
                treeGrids.Add(tree);
            }
            return treeGrids.Any() ? new Result { Code = 1, Message = "获取成功", Object = treeGrids } : new Result { Code = 0, Message = "获取失败" };
        }
        [ApiExplorerSettings(IgnoreApi = true)]
        private static List<TreeGridDto> GetChildrenTreeGridNode(List<ESysRoles> roles, ESysRoles role)
        {
            int parentid = role.Fid;
            List<TreeGridDto> dtos = new List<TreeGridDto>();
            var children = roles.Where(x => x.FparentId == parentid);

            foreach (var item in children)
            {
                TreeGridDto tree = new TreeGridDto
                {
                    nodeId = item.Fid,
                    nodeName = item.Fname,
                    nodeParentId = item.FparentId,
                    nodeSort = item.Fsort,
                    nodeRemark = item.Fremark,
                    nodeAddTime = item.FaddTime,
                    Childrens = GetChildrenTreeGridNode(roles, item)
                };
                dtos.Add(tree);
            }
            return dtos;
        }
        #endregion

        #region 获取角色下拉框
        /// <summary>
        /// 获取角色下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<Result> GetRoleTreeSelect()
        {
            List<ESysRoles> roles = await _dbContext.ESysRoles.ToListAsync<ESysRoles>();
            List<TreeSelectDto> selectDtos = new List<TreeSelectDto>();
            foreach (var item in roles.Where(x => x.FparentId == 0))
            {
                TreeSelectDto select = new TreeSelectDto
                {
                    nodeId = item.Fid,
                    nodeName = item.Fname,
                    Childrens = GetChildrenTreeSelectNode(roles, item)
                };
                selectDtos.Add(select);
            }
            return selectDtos.Any() ? new Result { Code = 1, Message = "获取成功", Object = selectDtos } : new Result { Code = 0, Message = "获取失败" };
        }

        private List<TreeSelectDto> GetChildrenTreeSelectNode(List<ESysRoles> roles, ESysRoles role)
        {
            int parentid = role.Fid;
            List<TreeSelectDto> dtos = new List<TreeSelectDto>();
            var children = roles.Where(x => x.FparentId == parentid);
            foreach (var item in children)
            {
                TreeSelectDto tree = new TreeSelectDto
                {
                    nodeId = item.Fid,
                    nodeName = item.Fname,
                    Childrens = GetChildrenTreeSelectNode(roles, item)
                };
                dtos.Add(tree);
            }
            return dtos;
        }
        #endregion

        #region 增加角色
        /// <summary>
        /// 增加角色
        /// </summary>
        /// <param name="role">角色dto</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<Result> AddRole([FromBody] RolesDto role)
        {
            if (ModelState.IsValid)
            {
                ESysRoles sysRoles = new ESysRoles
                {
                    FaddTime = DateTime.Now,
                    FmodifyTime = null,
                    Fname = role.FName,
                    FparentId = role.FParentID,
                    Fremark = role.FRemark,
                    Fsort = role.FSort
                };
                await _dbContext.ESysRoles.AddAsync(sysRoles);
                return await _dbContext.SaveChangesAsync() > 0 ? new Result { Code = 1, Message = "新增成功" } : new Result { Code = 0, Message = "新增失败" };
            }
            return new Result { Code = -1, Message = "模型验证未通过" };
        }
        #endregion

        #region 修改角色
        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="role">角色dto</param>
        /// <returns></returns>
        [HttpPut]
        public async Task<Result> ModifyRole([FromBody] RolesDto role)
        {
            if (!ModelState.IsValid) return new Result { Code = -1, Message = "模型验证未通过" };
            ESysRoles sysRoles = await _dbContext.ESysRoles.FirstOrDefaultAsync(x => x.Fid == role.FID);
            sysRoles.FmodifyTime = DateTime.Now;
            sysRoles.Fname = role.FName;
            sysRoles.FparentId = role.FParentID;
            sysRoles.Fremark = role.FRemark;
            sysRoles.Fsort = role.FSort;
            sysRoles.Fid = role.FID;
            _dbContext.ESysRoles.Update(sysRoles);
            return await _dbContext.SaveChangesAsync() > 0 ? new Result { Code = 1, Message = "修改成功" } : new Result { Code = 0, Message = "修改失败" };
        }
        #endregion

        #region 删除角色
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId">角色id</param>
        /// <returns></returns>
        [HttpDelete]
        public async Task<Result> DelRole(int roleId)
        {
            ESysRoles roles = await _dbContext.ESysRoles.FirstOrDefaultAsync(x => x.Fid == roleId);
            if (roles != null) _dbContext.ESysRoles.Remove(roles);
            return await _dbContext.SaveChangesAsync() > 0 ? new Result { Code = 1, Message = "删除成功" } : new Result { Code = 0, Message = "删除失败" };
        }
        #endregion
    }
}